/**
 * 
 */
package pers.vic.readlog.log.util;

import java.io.File;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import pers.vic.readlog.log.LogSocket;

/**
 * @author Vic.xu
 *
 */
public class LogWatchUtil {
	
	private static Logger logger = LoggerFactory.getLogger(LogWatchUtil.class);
	
	/**
	 * 要监听的文件的事件
	 */
	@SuppressWarnings("rawtypes")
	private static  WatchEvent.Kind [] EVENTS = { StandardWatchEventKinds.ENTRY_MODIFY };

	
	public static void init(String path) {
		Thread thread = new Thread(()->{
			realInit(path);
		});
		thread.setDaemon(true);
		thread.start();
	}
	
	/**
	 * 初始化文件监控 并阻塞
	 * @param path
	 */
	public static void realInit(String path) {
		logger.info(" LogWatch inti  " + path);
		try {
			Path dir = Paths.get(path);
			if(!dir.toFile().exists()) {
				logger.error("不存在的日志文件夹：{}", path);
				return;
			}
			WatchService watchService = FileSystems.getDefault().newWatchService();
			
			
			
			//StandardWatchEventKinds
			//这里监控文件的 创建、修改、删除  但是这里返回的key里面的监控信息为空
			WatchKey key = dir.register(watchService, EVENTS);
			while ( (key = watchService.take()) != null) {
				//利用 key.pollEvents() 方法返回一系列的事件列表 List<WatchEvent<?>> list
				for (WatchEvent<?> event: key.pollEvents()) {
				    //得到 监听的事件类型
				    @SuppressWarnings("unused")
					WatchEvent.Kind<?> kind = event.kind();
				    //得到 监听的文件/目录的路径
				    Path changed  = (Path) event.context();
				    Path absolute = dir.resolve(changed);
				    File file = absolute.toFile();
				    //给相应session发送信息
				    LogSocket.whenFileChange(file);
				    //每次得到新的事件后，需要重置监听池
				    key.reset();
				}
				
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
}
